const puppeteer = require("puppeteer-extra");
const fs = require("fs");
const utils = require("../utils");
const config = require("../config");
const getListing = require("./getListing");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
puppeteer.use(StealthPlugin());

module.exports = async (sellerId) => {
  let info = await utils.promisify(fs.readFile)(
    `./data/${sellerId}/${sellerId}.txt`,
    "utf-8"
  );
  let list = JSON.parse(info.replaceAll("][", ","));
  console.log(list);
  puppeteer
    .launch({
      headless: false,
      // args: ["--no-sandbox", "--disable-setuid-sandbox"],
      defaultViewport: {
        width: 1920,
        height: 1080,
      },
    })
    .then(async (browser) => {
      const page = await browser.newPage();
      page.setDefaultNavigationTimeout(3000000);

      // ------第一步 获得新的token-------------//
      // 进入amazon.com，修改邮编
      await page.goto(config.webSite + "dp/B0C6J61DDD");
      // 打开切换邮编弹窗
      await page.waitForSelector("#nav-global-location-data-modal-action");
      await page.click("#nav-global-location-data-modal-action");
      // 填写其他地址字段,洛杉矶
      await page.waitForSelector("#GLUXZipUpdateInput");
      await page.$eval("#GLUXZipUpdateInput", (el) => (el.value = "90001"));
      await page.waitForSelector("#GLUXZipUpdate");
      const hasClickBtn = await page.evaluate(() => {
        return !!document.querySelector("#GLUXZipUpdate-announce");
      });
      // return
      if (hasClickBtn) {
        await page.click("#GLUXZipUpdate-announce");
        await page.click("#GLUXZipUpdate");
      } else {
        await page.click("#GLUXZipUpdate");
        await page.click("#GLUXZipUpdate-announce");
      }

      await utils.sleep(2000);

      // 开始执行任务
      let space = 100;
      let infos = [];
      let listLen = list.length;
      // 获得asin信息
      for (i in list) {
        if (Number(i) % 20 === 0) {
          infos = [];
        }

        utils.sleep(Math.floor(Math.random() * (1500 - 500) + 500));
        console.log(`------${list[i].asin}正在获取------`);
        infos = infos.concat(await getListing(page, list[i].asin));
        if ((Number(i) + 1) % 20 === 0) {
          console.log(infos.map(v => v.asin).join(','),parseInt((Number(i) + 1) / 20) + 1)
          saveJSON(infos, parseInt((Number(i) + 1) / 20), sellerId);
        }
         if (listLen === Number(i) + 1) {
          saveJSON(infos, Math.ceil(listLen / 20), sellerId);
         }
      }

      function saveJSON(data, page, sellerId) {
        console.log(data.map(v => v.asin).join(','))
        const infoData = JSON.stringify(data, null, 2);
        fs.readFile(
          `./data/${sellerId}/${sellerId}-${page}.txt`,
          "utf-8",
          (err, info) => {
            fs.writeFileSync(`./data/${sellerId}/${sellerId}-${page}.txt`, infoData);
          }
        );
      }

      // 完成所有操作，关闭浏览器
      await browser.close();
    });
};
